class EntitiesController < ApplicationController
	skip_before_filter :authorize, :only => [:new,:create,:change_colour_scheme]
	skip_before_filter :store_path, :only => [:create_private_popsicle]
	skip_before_filter :authorise_user, :only => [:show_friend,:add_friend,:remove_friend_request,:create,:update,:show,:accept_friend_request,:deny_friend_request,:block_friend_request]

  # GET /entities
  # GET /entities.xml
  def index	
	@type = params[:type]
	@search_filter = "" #text displaying what filters have been put on the search
	all = []
	@entities = []
	if params[:search]
		current_user = Entity.find(session[:user_id])
		if @type == "User"
			all = User.find(:all, :conditions => ['name LIKE ? OR description LIKE ?', "%#{params[:search]}%",  "%#{params[:search]}%"])
			all.each do |e|
				if e.can_be_searched(current_user)
					@entities << e
				end
			end
			@search_filter += "Showing search results for users"
		elsif @type == "Group"
			all = Group.find(:all, :conditions => ['name LIKE ? OR description LIKE ?', "%#{params[:search]}%",  "%#{params[:search]}%"])
			all.each do |e|
				if e.can_be_searched(current_user)
					@entities << e
				end
			end
			@search_filter += "Showing search results for groups"
		else
			all = Entity.find(:all, :conditions => ['name LIKE ? OR description LIKE ?', "%#{params[:search]}%",  "%#{params[:search]}%"])
			all.each do |e|
				if e.can_be_searched(current_user)  
					@entities << e
				end
			end
			@search_filter += "Showing search results for users and groups"
		end
	else
		@entities = nil
	end

    respond_to do |format|
		format.html # index.html.erb
		format.xml  { render :xml => @entities }
    end
  end

  # GET /entities/1
  # GET /entities/1.xml
  def show #Adrian
	@entity = Entity.find(session[:user_id])
  	@friends = @entity.friends
  	@groups = @entity.find_groups
	@puddles = @entity.puddles
  	
  	@public_messages = @entity.public_messages
    @public_messages.sort! {|p1,p2| p2.created_at <=> p1.created_at}
  	@popsicle = Popsicle.new(:public_author_id => @entity.id)
	
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @entity }
    end
  end
  
  def show_friend #Michael, Adrian	
  	@current_user = Entity.find(session[:user_id])
  	@entity = Entity.find(params[:id])
  	@friends = @entity.friends
    
    @is_group = Group.exists?params[:id]
    @is_group_member = @is_group && @current_user.find_groups.include?(@entity)
    if (@is_group)
      if @entity.introverted
         @public_messages = @entity.introverted_stream
      else
        @public_messages = @entity.extraverted_stream
      end
    else
      @public_messages = @entity.public_messages.publicly_available
    end 
    
    @public_messages.sort! {|p1,p2| p2.created_at <=> p1.created_at}
  	@friend_of_friend = @entity.is_friend_of_friend(@current_user)
    
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @entity }
    end
  end

  def new_puddle
    respond_to do |format|
      format.html
      format.xml
    end
  end

  def create_puddle
    @entity = User.find(session[:user_id])
    @entity.create_puddle(params[:name])

    respond_to do |format|
      format.html {redirect_to(organise_friends_path, :notice => 'Puddle was successfully created')}
      format.xml {head :ok}
    end
  end

  def organise_friends
    @entity = User.find(session[:user_id])
    @friends = @entity.friends
    @cliques = []
    @entity.find_puddles.each do |p|
	unless p.name == "All Friends"
	    @cliques << p
	end
    end

    respond_to do |format|
	format.html
	format.xml {render :xml => @entity}
    end
  end

  def remove_from_group
    #get the clique
    @clique = Puddle.find(params[:clique_id])
    #check that the current user controls the clique
    @user = User.find(session[:user_id])
    if @user.puddles.include?(@clique)
      #Remove the provided member from the group
      @user.remove_entity_from_puddle(params[:member_id], @clique.id)
    else
      #User is trying to modify a clique it does not own
      #TODO   Do something about this
    end

    respond_to do |format|
      format.html { redirect_to(organise_friends_path) }
      format.xml
    end
  end

  def add_to_group
    #get the clique
    @clique = Puddle.find(params[:clique_id])
    #check that the current user controls the clique
    @user = User.find(session[:user_id])
    if @user.puddles.include?(@clique)
      #Add the provided member to the group
      @entity_to_add = User.find(params[:member_id])
      @user.add_entity_to_puddle(@entity_to_add.id, @clique.id)
    else
      #User is trying to modify a clique it does not own
      #TODO   Do something about this
    end

    respond_to do |format|
      format.html { redirect_to(organise_friends_path) }
      format.xml
    end
  end

  def new
    if session[:user_id].nil? 
      @entity = User.new
    else
      @entity = Group.new
    end
  
    respond_to do |format|
      format.html
      format.xml  { render :xml => @entity }
    end
  end

  # GET /entities/1/edit
  def edit
    @entity = Entity.find(params[:id])
    
    respond_to do |format|
    	format.html
    	format.xml { render :xml => @entity }
    end
  end
  
  def change_password
    @entity = User.find(params[:id])
    
    respond_to do |format|
    	format.html
    	format.xml { render :xml => @entity }
    end
  end
  
  def create
    if params[:user].nil?
      @entity = Group.new(params[:group])
    else
      @entity = User.new(params[:user])
    end 
    Notifier.account_creation(@entity).deliver #Michael               
  
    respond_to do |format|
      if @entity.save
        if session[:user_id].nil?
          session[:user_id] = @entity.id
          alert = 'Account was successfully created.'
        else
          alert = 'Group was successfully created.'
          @entity.initialise_relationships(session[:user_id])
        end
        format.html { redirect_to(entity_path(@entity), :alert => alert) }
        format.xml  { render :xml => @entity, :status => :created, :location => @entity }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @entity.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    @entity = Entity.find(params[:id])
    
    type_hash = (params[:group].nil?) ? params[:user] : params[:group] 
    
    respond_to do |format|
      if @entity.update_attributes(type_hash)
        if params[:user].nil?
          alert = 'Group settings were successfully updated.'
          path = show_friend_path(@entity)
        else
          alert = 'Account settings were successfully updated.'
          path = entity_path(@entity)
        end
        format.html { redirect_to(path, :alert => alert) }
        format.xml  { render :xml => @entity, :status => :created, :location => @entity }
      else
        format.html { redirect_to(:back, :alert => "Password change failed") }
        format.xml  { render :xml => @entity.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /entities/1
  # DELETE /entities/1.xml
  def destroy
    @entity = Entity.find(params[:id])
    @entity.destroy

    respond_to do |format|
      format.html { redirect_to(entities_url) }
      format.xml  { head :ok }
    end
  end
  
  def feed #Adrian
  	@entity = Entity.find(params[:id])
  	@feed = @entity.friends_stream
    @feed.sort! {|f1,f2| f2.created_at <=> f1.created_at}
  end
  
  def create_public_popsicle #Adrian/Michael	
  	@entity = Entity.find(session[:user_id])
  	@entity.create_public_message(params[:content],params[:group_author_id])
  	if Group.exists?(params[:group_author_id])
  		redirect_to(show_friend_path(Group.find(params[:group_author_id])))
  	else
  		redirect_to(entity_path(@entity))
  	end
  end
  
	def create_private_popsicle #Michael
		@entity = Entity.find(session[:user_id])

		respond_to do |format|
		  if @entity.create_private_message(params[:recipient_id], params[:subject], params[:content])
			format.html { redirect_to(session[:return_to], :alert => 'You successfully sent a private message to ' + Entity.find(params[:recipient_id]).name) }
			format.xml  { head :ok }
		  else
			format.html { render :action => "create_private_response", :alert => 'There was a problem sending your personal message' }
		  end
		end
	end

	def create_private_popsicle_for_group #Ethan
		@entity = Entity.find(session[:user_id])

		@puddle = Puddle.find(params[:recipient_id])
		@puddle.puddleMembers.each do |person|
			@entity.create_private_message(person.id, params[:subject], params[:content])
		end

		respond_to do |format|
			format.html { redirect_to(entity_path(session[:user_id]), :alert => 'Message sent to ' + Puddle.find(params[:recipient_id]).name) }
			format.xml { head :ok }
		end
	end

	def friend_requests_received
		@entity = Entity.find(params[:id])
		@friend_requests_received = @entity.friend_requests_received		
		@friend_requests_made = @entity.friend_requests_made		
	end

	def accept_friend_request 
		
		@friendship = Friendship.find(params[:id])
		@entity	= Entity.find(@friendship.friend_id)
		@entity.accept_friend_request(@friendship.entity_id)
		
		respond_to do |format|
			format.html { redirect_to(entity_path(@entity)) }
			format.xml  { head :ok }
		end
	end

	def deny_friend_request 
		entity = Entity.find(params[:id])
		@deny_friend_request = @entity.deny_friend_request
		
		respond_to do |format|
			format.html { redirect_to(entity_path(entity)) }
			format.xml  { head :ok }
		end
	end

	def block_friend_request 
		entity = Entity.find(params[:id])
		@block_friend_request = entity.block_friend_request
		
		respond_to do |format|
			format.html { redirect_to(entity_path(entity)) }
			format.xml  { head :ok }
		end
	end	  
  
	def add_friend
		entity = Entity.find(session[:user_id])
		success = false;
		if(User.exists?(params[:id]))
		  success = entity.request_friend(params[:id])
		  message = 'You have sent ' + Entity.find(params[:id]).name + ' a friend request'
		elsif(Group.exists?(params[:id]))
		  success = Friendship.create(:entity_id => session[:user_id], :friend_id => params[:id], :accepted => true)
		   message = 'You have joined ' + Entity.find(params[:id]).name
		end
		
		#redirect_to(entity_path(session[:user_id]))
		
		respond_to do |format|
		  if success
			  format.html { redirect_to(:back, :alert => message) }
			  format.xml  { head :ok }
		  else
			  format.html { redirect_to(:back, :alert => 'There was a problem sending your last request' )}
		  end
		end
	end
  
	def remove_friend_request
		Friendship.find_by_entity_id_and_friend_id_and_accepted(Entity.find(session[:user_id]), Entity.find(params[:id]), false).destroy
		
		respond_to do |format|
		  format.html { redirect_to(:back) }
		  format.xml  { head :ok }
		end
	end
	  
	def feedback_form #Michael
		@entity = Entity.find(session[:user_id])
	end
	
	def send_feedback #Michael
		Notifier.feedback(params[:sender], params[:subject], params[:content]).deliver
		redirect_to(entity_path(session[:user_id]))
	end	
	
	def change_colour_scheme #Adrian
		cookies[:colour_scheme] = params[:scheme]		
		redirect_to :back
	end
	
	def html_chat #Michael
		Notifier.feedback(session[:user_id], 
		"HTML Chat", "This user clicked the HTML Chat button.").deliver
	end
	
	def recent_activity #Michael
		@entity = Entity.find(session[:user_id])
		@new_messages = @entity.new_messages.sort! {|f1,f2| f2.created_at <=> f1.created_at}
		@friend_requests = Friendship.find_all_by_friend_id_and_accepted(@entity.id, false)
		
		@new_messages.each do |m|
			m.update_attribute(:updated_at, Time.now)
		end
	end
end
